package com.zhouyu.gamecommunity.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.zhouyu.gamecommunity.contants.ResultCode;
import com.zhouyu.gamecommunity.contants.Sex;
import com.zhouyu.gamecommunity.entity.Result;
import com.zhouyu.gamecommunity.entity.User;
import com.zhouyu.gamecommunity.dao.UserMapper;
import com.zhouyu.gamecommunity.entity.queryParams.LoginParam;
import com.zhouyu.gamecommunity.service.CommonService;
import com.zhouyu.gamecommunity.service.UserService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Random;

/**
 * @description user
 * @author zhouyu
 * @date 2025-06-07
 */
@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;
	@Resource
	private CommonService commonService;


	@Override
	public Result<User> userLogin(LoginParam loginParam) {
		User user = userMapper.findByPhone(loginParam.getAccount());
		if (user == null) {
			return Result.fail(ResultCode.USER_NOT_EXIST);
		}
		if (loginParam.getVerifyCode() != null) {
			//验证码登录
			if (loginParam.getVerifyCode().equals(commonService.createVerifyCode(loginParam.getAccount()))) {
				//登录成功
				return Result.success(user);
			}
			return Result.fail("验证码错误!");
		}else {
			//账号密码登录
			String loginPassword = SecureUtil.md5(user.getId() + loginParam.getPassword());
			if (user.getPassword().equals(loginPassword)) {
				//登录成功
				return Result.success(user);
			}else {
				//登录失败
				return Result.fail("账号或密码错误!");
			}
		}
    }

	@Override
	public Result<Integer> userRegister(LoginParam loginParam) {
		//验证码校验
		if (!loginParam.getVerifyCode().equals(commonService.createVerifyCode(loginParam.getAccount()))) {
			//验证失败
			return Result.fail("验证码错误!");
		}
		//参数赋值
		String id = IdUtil.getSnowflake().nextIdStr();
		User user = new User();
		user.setId(id);
		user.setUsername("用户_" + id);
		user.setPassword(SecureUtil.md5(id + loginParam.getPassword()));
		user.setSex(Sex.SECRET.getCode());
		user.setFansNum(0);
		user.setFollowNum(0);
		user.setGuestNum(0);
		user.setPhone(loginParam.getAccount());
		user.setIntroduction("这个人很懒，什么都没留下");
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());

		return Result.success(userMapper.insert(user));
	}

	@Override
	public Result<User> getUserById(String userId) {
		return Result.success(userMapper.load(userId));
	}

	@Override
	public Result<Integer> updateUserById(User user) {
		return Result.success(userMapper.update(user));
	}
}